function numIslands(grid){
    let fatherMap = new Map()
    let m = grid.length
    let n = grid[0].length
    // 初始化团队，每个团队的队长
    for(let i=0; i<m; i++){
        for(let j=0; j<n; j++){
            if(grid[i][j] == 1){
                fatherMap.set(JSON.stringify([i,j]), JSON.stringify([i,j]))
            }
        }
    }
    console.log(fatherMap)

    for(let i=0; i<m; i++){
        for(let j=0; j<n; j++){
            if(grid[i][j] == 1){
                grid[i][j] = 0
               if(i+1 < m && grid[i+1][j] == 1) union(JSON.stringify([i,j]), JSON.stringify([i+1, j]))
               if(i-1>0 && grid[i-1][j] == 1) union(JSON.stringify([i,j]), JSON.stringify([i-1, j]))
               if(j+1 <n && grid[i][j+1] == 1) union(JSON.stringify([i,j]), JSON.stringify([i, j+1]))
               if(j-1>0 && grid[i][j-1] == 1) union(JSON.stringify([i,j]), JSON.stringify([i, j-1]))
            }
        }
    }
    let arr = []
    for (const [key, value] of fatherMap) {
        if(!arr.includes(value)){
            arr.push(value)
        }
    }
    console.log(arr, fatherMap)
    
    // 查找队长
    function find(x){
        if(!fatherMap.has(x)){
            return null
        }
        let father = x
        while(father != fatherMap.get(father)){
            father = fatherMap.get(father)
        }
        return father
    }

    // 合并两个团队
    function union(t1, t2){
        let f1 = find(t1) //查找团队1的队长
        let f2 = find(t2) //查找团队2的队长
        
        if(!f1 || !f2 ) return null
        let v1 = grid[JSON.parse(f1)[0]][JSON.parse(f1)[1]]
        let v2 = grid[JSON.parse(f2)[0]][JSON.parse(f2)[1]]
        console.log(t1,t2,f1, f2, v1, v2)
        if( v1 == 0){
            fatherMap.set(f2, f1)
            grid[JSON.parse(f2)[0]][JSON.parse(f2)[1]] = 0
        }else if(v2 == 0){
            fatherMap.set(f1, f2)
            grid[JSON.parse(f1)[0]][JSON.parse(f1)[1]] = 0
        }else{
            console.log(111111111)
            fatherMap.set(f2, f1)
        }
        
    }

    
}

let grid =[
    ["1","0","1","1","1"],
    ["1","0","1","0","1"],
    ["1","1","1","0","1"]
]
  

  
numIslands(grid)